/*
 *
 *  * Copyright (c) 2016. For Intelligent Group.
 *
 */

package com.intelligent.ispc.core.functional.python;

import com.intelligent.ispc.common.mapper.JsonMapper;
import com.intelligent.ispc.foundation.io.ProcessStreamHelper;
import com.intelligent.ispc.foundation.io.ResourceFinder;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * Created by Peter on 2016/8/17.
 */
public class ImportScriptT {

    public static void main(String args[]) throws IOException, InterruptedException {
        JsonMapper mapper = new JsonMapper();
        ResourceFinder rf = new ResourceFinder("pyscripts");

        String path = rf.findResource("UserScript.py").getPath();
        String path2 = rf.findResource("pyscripts/aa.csv").getPath();
        Process p = Runtime.getRuntime().exec("python " + path + " " +path2);
        final String[] result = new String[4];
        final int[] index = {0};
        ProcessStreamHelper errorGobbler = new ProcessStreamHelper(p.getErrorStream(), ProcessStreamHelper.ERROR);
        ProcessStreamHelper outputGobbler = new ProcessStreamHelper(p.getInputStream(), ProcessStreamHelper.OUTPUT,
                new ProcessStreamHelper.ProcessCallBack() {
                    @Override
                    public void readAll(List<String> arg) {
                       // result[index[0]]arg;
                        index[0]++;
                    }
                });
        errorGobbler.start();
        outputGobbler.start();
        p.waitFor();

        String param = result[0].substring(11, result[0].length());
        String data = result[1].substring(10, result[1].length());

        //DATA_PARAM
        Map<String, Object> paramMap = mapper.fromJson(param, Map.class);
        for (String key : paramMap.keySet()) {
            String row = (String) paramMap.get(key);
            System.out.println("field:" + key + ", value:" + row);
        }

        //DATA_INFO
        List<Map> dataList = mapper.fromJson(data, List.class);
        for (int i = 0; i < dataList.size(); i++) {
            Map<String, String> row = dataList.get(i);
            for (String s : row.keySet()) {
                System.out.println(s + ":" + row.get(s));
            }
        }
    }

}
